package com.example.phones;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.Phones;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		ListView lv = (ListView)findViewById(android.R.id.list);
		Cursor cursor = getContentResolver().query(Phones.CONTENT_URI, null, null, null,  Phones.NAME + " ASC");
		startManagingCursor(cursor);
		ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[]{Phones.NAME, Phones.NUMBER}, new int[]{android.R.id.text1,android.R.id.text2});
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Cursor c = getContentResolver().query(Phones.CONTENT_URI, null, Phones._ID + "=?", new String[]{String.valueOf(id)}, null);
				if(c.moveToFirst()){
					Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + c.getString(c.getColumnIndex(Phones.NUMBER))));
					startActivity(intent);
				}
				c.close();
			}
			
		});

			
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
